<?php
/**
 * (model) 备货sku预估（全站点）
 */
namespace App\Models\SsBasic;

use Illuminate\Database\Eloquent\Model;
class AreaSkuEstimate extends Model
{
    protected $table = 's_area_sku_estimate';

    protected $guarded = [];

    const ESTIMATE_NUM = 18;

    const NEW_ESTIMATE_NUM = 9; //预估月份（9个月）

    /**
     * 获取预估数组
     * @param $model
     * @return array
     */
    public static function getEstimate($model){
        $num = self::ESTIMATE_NUM;
        $estimate = [];
        for($i = 0; $i < $num; $i++){
            $estimate['estimate_num'.$i] = ($model->{'estimate_num'.$i}) ?? 0;
        }
        return $estimate;
    }

    /**
     * 获取库存系数
     * @param       $inventory
     * @param array $estimateNum
     * @return float|int|string
     */
    public static function getInventoryFactor($inventory,$estimateNum = []){
        $num = self::ESTIMATE_NUM - 1;
        $sum = 0;
        $k = 0;
        $count = 0;
        for($i = 0; $i <= $num; $i++){
            $sum += $estimateNum['estimate_num'.$i]; //sku总预估数量(备货月份汇总)
            if($inventory <= $sum){
                $k = $i; //sku库存不满足预估总量的备货月份
                break;
            }
            $count++; //验证后,满足条件的总备货月份数量
        }
        if($count == self::ESTIMATE_NUM){
            //满足备货的所有月份
            if($inventory == $sum){
                $factor = self::ESTIMATE_NUM; //所有月份
            }else{
                $factor = self::ESTIMATE_NUM.'+'; //超出备货库存总量(所有月份)的标记 (18+)
            }
        }else{
            //不满足备货月份
            $sum2 = 0;
            $factor = 0;
            for ($j = 0; $j < $k; $j++){
                $sum2 += $estimateNum['estimate_num'.$j]; //不满足备货月份的sku总预估数量(月份汇总)
                $factor++;
            }
            if($estimateNum['estimate_num'.$k] == 0){
                $factor += 0;
            }else{
                //库存系数 = 库存余量(sku总库存 - 已满足备货月份的sku总预估数量) / 不满足备货月份的sku预估数量
                $factor += round(($inventory - $sum2) / $estimateNum['estimate_num'.$k],3);
            }
        }
        return $factor;
    }
}
